package com.crl.module.loaders
{
	import com.crl.module.loaders.workers.ILoadWorker;
	
	import flash.net.URLRequest;
	import flash.utils.Dictionary;
	
	
	/**
	 * 简单worker 工厂;
	 * @author crl
	 * 
	 */	
	public class WorkerFactory
	{
		private static var types:Dictionary;
		public static function addWorkerType(type:String, klass:Class):void
		{
			if(types==null)types=new Dictionary();
			types[type]=klass;
		}
		
		public static function getWorkerInstance(type:String):ILoadWorker{
			if(!types[type]){
				throw new Error("Worker of type {" + type + "} was not registered. Register a Class reference to it first.");
			}
			var klass:Class = types[type] as Class;
			var instance:ILoadWorker = new klass();
			return instance;
		}
		
		
		/**
		 * 创建一个worker ; 
		 * @param source
		 * @return 
		 * 
		 */		
		public static function create(source:String):ILoadWorker{
			var filenameRegEx:RegExp = new RegExp("\.([a-zA-Z0-9]*$)","i");
			var filematch:Array = source.match(filenameRegEx);
			if(filematch==null){
				return null;
			}
			var fileType:String = filematch[1].toLowerCase();

			var instance:ILoadWorker=getWorkerInstance(fileType);
			instance.load(new URLRequest(source));
			return instance;
		}
	}
}